import React, { useState, useEffect } from 'react';
import { Tabs, Cell, Notify, Flex, Tag, Pagination, Button, Input, hooks, Popup, Card, Circle } from 'react-vant';
import TopNav from '../../components/TopNav/TopNav';
import axios from 'axios';
import { Ellipsis, Plus } from '@react-vant/icons';
import { useNavigate } from 'react-router-dom';

const items = ["信息", "任务"];

const Staff = () => {
    const navigate = useNavigate();
    const [visible, setVisible] = useState(false);
    const [state, updateState] = hooks.useSetState({
        text: '',
    });
    const [page, setPage] = useState(1); // 当前员工页码
    const [taskPage, setTaskPage] = useState(1); // 当前任务页码
    const [pageSize] = useState(5); // 每页显示的数量
    const [staffList, setStaffList] = useState([]);
    const [taskList, setTaskList] = useState([]);

    // 获取数据
    const fetchData = async () => {
        try {
            const staffResponse = await axios.get('http://192.168.0.154:3000/my/posts');
            setStaffList(staffResponse.data);

            const taskResponse = await axios.get('http://192.168.0.154:3000/my/posts');
            setTaskList(taskResponse.data);
        } catch (error) {
            console.error('数据获取失败:', error);
        }
    };

    // 正则表达式：检查邮箱格式是否正确
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

    // 提交表单，添加员工
    const handleSubmit = async () => {
        // 判断邮箱格式是否正确
        if (!emailRegex.test(state.text)) {
            Notify.show({ type: 'warning', message: '请输入有效的邮箱地址' });
            return;
        }

        try {
            // 这里不需要 .Emall，直接用 response.data 即可
            const response = await axios.get(`http://192.168.0.154:3000/my/Emall?email=${state.text}`);
    
            // 假设你返回的是一个数组，使用 .some() 检查 email 是否存在
            const emailExists = response.data.some(item => item.email === state.text);
    
            if (emailExists) {
                const postData = response.data[0];  // 获取找到的第一个匹配的用户数据
                postData.id = postData.id || Date.now();  // 如果没有 id，使用时间戳作为 ID
    
                // 提交到后端
                 await axios.post('http://192.168.0.154:3000/my/posts', postData);
                 Notify.show({ type: 'success', message: '添加成功' })
                // 清空
                updateState({ text: '' })
    
                // 重新获取数据
                fetchData();
            } else {
                Notify.show({ type: 'warning', message: '邮箱不存在' })
                updateState({ text: '' })
            }
        } catch (error) {
            console.error('请求失败:', error);
            Notify.show({ type: 'danger', message: '请求失败' })
            updateState({ text: '' })
        }
    };

    // 获取数据在首次加载时调用
    useEffect(() => {
        fetchData();
    }, []);

    // 计算当前页面的员工列表
    const currentStaffList = staffList.slice((page - 1) * pageSize, page * pageSize);

    // 计算当前页面的任务列表
    const currentTaskList = taskList.slice((taskPage - 1) * pageSize, taskPage * pageSize);

    return (
        <div style={{ width: '100%', height: '100vh', overflowY: "auto", backgroundColor: 'rgb(244,249,253)', border: '1px solid transparent' }}>
            <TopNav />
            <div style={{ width: '335px', margin: '0 auto' }}>
                <h2 style={{ margin: '20px 0px 20px 10px' }}>员工({staffList.length})</h2>

                <div className='demo-tabs'>
                    <Tabs border type='capsule' >
                        {items.map((item) => (
                            <Tabs.TabPane key={item} title={item}  >
                                <div>
                                    {/* 信息 Tab */}
                                    {item === "信息" && (
                                        <div style={{ padding: '0px 0px 40px 0px' }}>
                                            {currentStaffList.map((staffMember, index) => (
                                                <div key={index} style={{ width: '100%', height: "244px", backgroundColor: 'white', borderRadius: '15px', margin: '20px 0', display: 'block' }}
                                                    onClick={() => {
                                                        localStorage.setItem('index', index);
                                                        navigate('/my');
                                                    }}
                                                >
                                                    <Cell
                                                        title={staffMember.name}
                                                        value={<Ellipsis />}
                                                        label={staffMember.email}
                                                        size="large"
                                                        icon={
                                                            <Circle
                                                                clockwise={false}
                                                                layerColor='rgb(244,249,253)'
                                                                rate={70} // 进度
                                                                speed={100}
                                                                style={{
                                                                    position: 'relative',
                                                                    width: '50px', // 控制Circle的大小
                                                                    height: '50px',
                                                                    backgroundImage: `url(${staffMember.avatar})`, // 设置头像为背景
                                                                    backgroundSize: '80%', // 修改背景大小以缩小图片
                                                                    backgroundPosition: 'center', // 让头像居中
                                                                    borderRadius: '50%', // 确保是圆形
                                                                }}
                                                            />
                                                        }
                                                        style={{ borderRadius: '15px' }}
                                                    />
                                                    <hr style={{ borderWidth: '1px', borderColor: 'rgb(228, 230, 232)', borderStyle: 'solid', width: '90%', margin: '0 auto', marginTop: '20px' }} />
                                                    <Flex style={{ color: 'rgb(145, 146, 158)', width: '90%', margin: '0 auto', textAlign: 'left', marginTop: '20px' }}>
                                                        <Flex.Item span={6}>性别</Flex.Item>
                                                        <Flex.Item span={12}>生日</Flex.Item>
                                                        <Flex.Item span={6}>年龄</Flex.Item>
                                                    </Flex>
                                                    <Flex style={{ width: '90%', margin: '0 auto', textAlign: 'left', marginTop: '10px' }}>
                                                        <Flex.Item span={6}>{staffMember.gender}</Flex.Item>
                                                        <Flex.Item span={12}>{staffMember.birthday}</Flex.Item>
                                                        <Flex.Item span={6}>{staffMember.age}</Flex.Item>
                                                    </Flex>
                                                    <Flex style={{ color: 'rgb(145, 146, 158)', width: '90%', margin: '0 auto', textAlign: 'left', marginTop: '20px' }}>
                                                        <Flex.Item span={6}>职位</Flex.Item>
                                                    </Flex>
                                                    <Flex style={{ width: '90%', margin: '0 auto', textAlign: 'left', marginTop: '10px' }}>
                                                        <Flex.Item span={12}>{staffMember.posts}</Flex.Item>
                                                        <Flex.Item span={3}>
                                                            <Tag plain type="primary">
                                                                {staffMember.grade}
                                                            </Tag>
                                                        </Flex.Item>
                                                    </Flex>
                                                </div>
                                            ))}
                                            <div style={{ width: '89%', position: 'fixed', bottom: '0px', background: 'rgb(244,249,253', margin: '0 auto' }}>
                                                <Pagination value={page} mode="simple" onChange={setPage} pageCount={Math.ceil(staffList.length / pageSize)} />
                                            </div>

                                            <div style={{ width: '56px', height: '56px', backgroundColor: 'rgb(63, 140, 255)', position: 'fixed', right: '5px', bottom: '60px', borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center' }} onClick={() => setVisible(true)}>
                                                <Plus />
                                                {/* 弹出框 */}
                                                <Popup visible={visible} onClose={() => setVisible(false)} style={{ borderRadius: '15px' }} closeable>
                                                    <div style={{ width: '320px', height: '313px' }}>
                                                        <Card>
                                                            <Card.Header>添加员工</Card.Header>
                                                            <Card.Body>
                                                                <p style={{ marginTop: '20px' }}>员工邮箱</p>
                                                                <Cell style={{ border: '1px solid rgb(223, 223, 223)', borderRadius: '15px', marginTop: '20px' }}>
                                                                    <Input
                                                                        value={state.text}
                                                                        onChange={text => updateState({ text })}
                                                                        placeholder='请输入邮箱'
                                                                        clearable
                                                                    />
                                                                </Cell>
                                                                <p style={{ marginTop: '20px', color: 'rgb(63, 140, 255)' }}>+继续添加</p>
                                                                <div className='demo-button' style={{ marginTop: '20px' }}>
                                                                    <Button type='primary' block round onClick={handleSubmit}>
                                                                        提交
                                                                    </Button>
                                                                </div>
                                                            </Card.Body>
                                                        </Card>
                                                    </div>
                                                </Popup>
                                            </div>
                                        </div>
                                    )}

                                    {/* 任务 Tab */}
                                    {item === "任务" && (
                                        <div style={{ padding: '0px 0px 40px 0px' }}>
                                            {currentTaskList.map((taskItem, index) => (
                                                <div key={index} style={{ width: '100%', height: "315px", backgroundColor: 'white', borderRadius: '15px', margin: '20px 0', overflow: 'hidden' }}>
                                                    <div style={{ width: '319px', height: '186px', backgroundColor: 'rgb(244, 249, 253)', margin: '0 auto', borderRadius: '20px', marginTop: '10px', overflow: 'hidden' }}
                                                        onClick={() => {
                                                            axios.get('http://192.168.0.154:3000/my/cats').then(res => {
                                                                console.log(res.data)
                                                            })
                                                        }}
                                                    >
                                                        <Cell
                                                            label={taskItem.email}
                                                            size="large"
                                                            icon={
                                                                <Circle
                                                                    clockwise={false}
                                                                    layerColor='rgb(244,249,253)'
                                                                    rate={taskItem.age2 > 0 ? (taskItem.age3 / taskItem.age2) * 100 : 0}
                                                                    speed={100}
                                                                    style={{
                                                                        margin: '0 auto',
                                                                        position: 'relative',
                                                                        width: '50px', // 控制Circle的大小
                                                                        height: '50px',
                                                                        backgroundImage: `url(${taskItem.avatar})`, // 设置头像为背景
                                                                        backgroundSize: '80%', // 修改背景大小以缩小图片
                                                                        backgroundPosition: 'center', // 让头像居中
                                                                        borderRadius: '50%', // 确保是圆形
                                                                    }}
                                                                />
                                                            }
                                                            style={{ borderRadius: '15px', backgroundColor: 'rgb(244, 249, 253)' }}
                                                        />
                                                        <div style={{ textAlign: 'center', marginTop: '3px' }}>{taskItem.name}</div>
                                                        <div style={{ textAlign: 'center', marginTop: '20px' }}>{taskItem.posts}</div>
                                                        <div style={{ textAlign: 'center', marginTop: '20px' }}>
                                                            <Tag plain type="primary">
                                                                {taskItem.grade}
                                                            </Tag>
                                                        </div>
                                                    </div>
                                                    <Flex gutter={[10, 20]} wrap='wrap' style={{ textAlign: 'center', marginTop: '20px', fontSize: '25px' }}>
                                                        <Flex.Item span={8}>{taskItem.age1}</Flex.Item>
                                                        <Flex.Item span={8}>{taskItem.age2}</Flex.Item>
                                                        <Flex.Item span={8}>{taskItem.age3}</Flex.Item>
                                                    </Flex>
                                                    <div style={{ width: '100%', display: 'flex', justifyContent: 'space-around', alignItems: 'center', marginTop: '10px', textAlign: 'center', color: 'rgb(145, 146, 158)' }}>
                                                        <div style={{ width: '60px' }}>待开始任务</div>
                                                        <div style={{ width: '60px' }}>进行中任务</div>
                                                        <div style={{ width: '60px' }}>已审查任务</div>
                                                    </div>
                                                </div>
                                            ))}
                                            <div style={{ width: '89%', position: 'fixed', bottom: '0px', background: 'rgb(244,249,253', margin: '0 auto' }}>
                                                <Pagination value={taskPage} mode="simple" onChange={setTaskPage} pageCount={Math.ceil(taskList.length / pageSize)} />
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </Tabs.TabPane>
                        ))}
                    </Tabs>
                </div>
            </div>
        </div>
    );
};

export default Staff;
